<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Core\Common\Helper;

use Core\Common\Base\RoundRobin;
use Core\Common\Base\Service;

/**
 * Description of ServiceRequest
 *
 * @author baiyang@ibantang.com
 */
class ServiceRequest
{
    public static function getService($service, $proto = 'http')
    {
        $targets = Service::getService($service, $proto);
        if ($targets) {
            $srvId = Service::getServiceId($service, $proto);
            $c = RoundRobin::incr($srvId);
            return $targets[$c % count($targets)];
        }
        return null;
    }

    public static function get($service, $uri, $data = [], $header = [], $options = [])
    {
        $host = self::getService($service);
        if (empty($host)) {
            return null;
        }
        return HttpClient::get($host, $uri, $data, $header, $options);
    }

    public static function post($service, $uri, $data = [], $header = [], $options = [])
    {
        $host = self::getService($service);
        if (empty($host)) {
            return null;
        }
        return HttpClient::post($host, $uri, $data, $header, $options);
    }

    public static function postJson($service, $uri, $data = [], $header = [], $options = [])
    {
        $host = self::getService($service);
        if (empty($host)) {
            return null;
        }
        return HttpClient::postJson($host, $uri, $data, $header, $options);
    }

    public static function put($service, $uri, $data = [], $header = [], $options = [])
    {
        $host = self::getService($service);
        if (empty($host)) {
            return null;
        }
        return HttpClient::put($host, $uri, $data, $header, $options);
    }
}
